<?php

namespace app\admin\controller;

use app\BaseController;
use app\common\model\AccountModel;

class Account extends BaseController
{
    /**
     * @var  AccountModel
     */
    private $model;

    public function initialize()
    {
        $this->model = new AccountModel();
    }


    public function index()
    {
        $result = [
            "status" => "no",
            "data" => [],
            "msg" => "查找失败"
        ];
        $option = $this->option();
        $result["status"] = "ok";
        $result["msg"] = "查找成功";
        $result["data"] = $this->model->pageData($option, 'account_name');


        return json($result);
    }

    public function create()
    {
        $result = [
            "status" => "no",
            "data" => [],
            "msg" => "查找失败"
        ];
        $insertData = [
            'account_name' => $this->request->param("name", ""),
            'nick_name' => $this->request->param("nick", ""),
            'account_pwd' => $this->request->param("password", ""),
            'type' => $this->request->param("type", "1"),
        ];

        if (empty($insertData["account_name"])) {
            $result["msg"] = "请输入账号名称";
            return json($result);
        }
        if (empty($insertData["account_pwd"])) {
            $result["msg"] = "请输入账号密码";
            return json($result);
        }
        if (empty($insertData["type"])) {
            $result["msg"] = "请选择账号类型";
            return json($result);
        }
        $insertData['account_pwd'] = $this->model->password($insertData['account_pwd']);

        $result = $this->model->saveData($insertData);
        return json($result);
    }

    public function update()
    {
        $result = [
            "status" => "no",
            "data" => [],
            "msg" => "查找失败"
        ];
        $id = $this->request->param("id", 0);
        $infoData = $this->request->param("info", "");
        if (empty($id)) {
            $result["msg"] = "id参数缺少";
            return json($result);
        }
        if (empty($infoData)) {
            $result["msg"] = "info参数缺少";
            return json($result);
        }
        $info = $infoData;
        $updateData = [
            'account_name' => $info["name"],
            'nick_name' => $info["nick"],
            'type' => $info["type"],
        ];
        $pwd = $info["password"];
        if ($pwd) {
            $updateData['account_pwd'] = $this->model->password($pwd);
        }
        $updateData['limits'] = implode(',', $info['limits']);

        $result = $this->model->editData($id, $updateData);
        return json($result);
    }

}
